﻿<!DOCTYPE html>

<html>
    <head>
        <title>Vanilla MSAL.JS</title>
        <meta charset="utf-8" />
        <style type="text/css">body { font-family: Tahoma; padding: 3em; }</style>
        <script src="dist/msal.js" class="pre"></script>
    </head>

    <body>
        <a href=".\">&lt; Back</a>
        <h4>MSAL+ LoginRedirect</h4>
        <p>
            <a id="login_button" href="#" onclick="login(); return false;">Log in</a>
            <a id="logout_button" href="#" onclick="logout(); return false;">Log out</a>
            <a id="callWebApi_button" href="#" onclick="callWebApi(); return false;">Call web api</a>

        </p>

        <p id="username"></p>
        <pre id="api_response"></pre>

        <script type="text/javascript">
            document.getElementById('login_button').style.display = "none";
            document.getElementById('logout_button').style.display = "none";
            document.getElementById('callWebApi_button').style.display = "none";
            document.getElementById('username').textContent = 'Loading...';


            function loggerCallback(logLevel, message, piiLoggingEnabled) {
                console.log(message);
            }     

            var logger = new Msal.Logger(loggerCallback, { level: Msal.LogLevel.Verbose, correlationId:'12345' }); // level and correlationId are optional parameters.
		
            // Set up MSAL
            var applicationConfig = {
                clientID: '9f064d41-aa20-4561-9aa5-d1a63f2c6130',
                graphEndpoint: "https://graph.microsoft.com/v1.0/me/sendMail",
                graphScopes: ["user.read", "mail.send"],
                authority: "https://login.microsoftonline.com/microsoft.onmicrosoft.com/",
                logger: logger
            };

            var clientApplication = new Msal.UserAgentApplication(applicationConfig.clientID, applicationConfig.authority, authCallback, { cacheLocation: "localStorage", state: "12345" });

            function authCallback(errorDesc, token, error, tokenType, state) {
                console.log("State received in the response:" + state);
                if (token) {
                    console.log("token received " + token);
                    document.getElementById('username').textContent = "User successfully logged in";
                    document.getElementById('logout_button').style.display = "block";
                    document.getElementById('login_button').style.display = "none";
                    document.getElementById('callWebApi_button').style.display = "block";
                }
                else if (errorDesc || error) {
                    console.log(error + ':' + errorDesc);
                }
            }

            function login() {
                clientApplication.loginRedirect();
            }

            function logout() {
                if (clientApplication) {
                    clientApplication.logout();
                    document.getElementById('logout_button').style.display = "none";
                }
            }

            function callWebApi()
            {
                clientApplication.acquireTokenSilent(applicationConfig.graphScopes).then(function (access_token) {
                    var xhr = new XMLHttpRequest();
                    xhr.open('GET', 'https://graph.microsoft.com/v1.0/me', true);
                    xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState === 4 && xhr.status === 200) {
                            document.getElementById('api_response').textContent = JSON.stringify(JSON.parse(xhr.responseText), null, '  ');
                            document.getElementById('callWebApi_button').style.display = "none";

                        } else {
                            document.getElementById('api_response').textContent = 'ERROR:\n\n' + xhr.responseText;
                        }
                    };

                    xhr.send();
                }, function (error) {
                    console.log(error);
                    clientApplication.acquireTokenPopup(applicationConfig.graphScopes).then(function (access_token) {
                        var xhr = new XMLHttpRequest();
                        xhr.open('GET', 'https://graph.microsoft.com/v1.0/me', true);
                        xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);
                        xhr.onreadystatechange = function () {
                            if (xhr.readyState === 4 && xhr.status === 200) {
                                document.getElementById('api_response').textContent = JSON.stringify(JSON.parse(xhr.responseText), null, '  ');
                                document.getElementById('callWebApi_button').style.display = "none";
                            } else {
                                document.getElementById('api_response').textContent = 'ERROR:\n\n' + xhr.responseText;
                            }
                        };
                        xhr.send();
                    }, function (error) {
                        console.log(error);
                        document.getElementById('api_response').textContent = error;
                    });
                });
            }

            document.getElementById('username').textContent = 'Loading...'; 
            var user = clientApplication.getUser();
                    if (!user) {
                        console.log("getUser returned null");
                        document.getElementById('username').textContent = '';
                        document.getElementById('login_button').style.display = "block";
                    }
                    else {
                        document.getElementById('username').textContent = "Welcome " + user.name;
                        console.log("user " +  JSON.stringify(user));
                        document.getElementById('logout_button').style.display = "block";
                        document.getElementById('callWebApi_button').style.display = "block";
                    }

        </script>
    </body>
</html>
